package swind.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import swind.web.entities.ExamUser;
import swind.web.service.IVoMachine;
import swind.web.service.ILoginService;
import swind.web.vo.LoginUserVo;

@Controller
public class LoginController {
	
	@Resource(name="loginServiceImp")
	ILoginService loginServiceImp;
	
	@Resource(name="voMachine")
	IVoMachine voMachine;

	
	@RequestMapping(value="login/index")
	public String showLogin(Model model,HttpSession session){
		
		if(session.getAttribute("user")!=null){
			if(loginServiceImp.isPasswordTrue((LoginUserVo)session.getAttribute("user"))){
				return "mainPages/main";
			}
		}
		
		model.addAttribute("loginVo",new LoginUserVo());
		return "login/index";
	}
	
	@RequestMapping(value="login/login",method=RequestMethod.POST)
	public String tomain(LoginUserVo loginVo,HttpSession session){
		//System.out.println("tomain");
		
		ExamUser eu=loginServiceImp.getUserByName(voMachine.VoToEntity(loginVo));
		if(eu==null){
			System.out.println("用户不存在，请重新输入");
			return "login/index";
		}
		
		if(loginServiceImp.isCrossLockTime(eu)){
			if(loginServiceImp.isPasswordTrue(loginVo, eu)){
				loginServiceImp.clearLoginFailCount(eu);
				session.setAttribute("user", voMachine.EntityToVo(eu));
				session.setAttribute("role", voMachine.EntityToVo(loginServiceImp.getRoleByExamUser(eu).get(0)));
				return "mainPages/main";
			}else{
				
				if(eu.getLoginFailCount()>=(byte)3){
					System.out.println("锁定时间,5分钟后重新操作");
					loginServiceImp.lockNow(eu);
					loginServiceImp.clearLoginFailCount(eu);
					return "login/index"; 
				}else if(eu.getLoginFailCount()<(byte)3){
					loginServiceImp.addLoginFailCount(eu);
					System.out.println("密码错误");
					
				}
				return "login/index"; 
			}
		}else{
			System.out.println("锁定时间内,5分钟后重新操作");
		}
		
		return "login/index";
	}
	
	@RequestMapping(value="login/logout")
	public String loginOut(HttpSession session){
		session.removeAttribute("user");
		session.removeAttribute("role");
		return "redirect:/login/index";
	}
}
